/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package pers.sakurasora.lesson.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pers.sakurasora.lesson.dao.OrderDao;
import pers.sakurasora.lesson.dao.OrderDetailDao;
import pers.sakurasora.lesson.dto.OrderDto;
import pers.sakurasora.lesson.entity.BizOrderDetail;
import pers.sakurasora.lesson.service.OrderService;
import pers.sakurasora.lesson.service.ProductService;

/**
 * @author SakuraSora
 * @Email 1468071675@qq.com
 * @DateTime 2018-11-5 9:17:41
 *
 * @Description
 *              服务层（业务逻辑层）实现类--下订单
 */
@Service /*标注它是一个Service组件;
           需要在applicationContext.xml文件中配置<context:component-scan base-package="pers.sakurasora.lesson.service.impl"/>,
           注记才会生效，才会作为一个组件注册到spring的容器中去*/
public class OrderServiceImpl implements OrderService{

     @Autowired//自动依赖注入--业务逻辑层要依赖于DAO层，去访问DAO层
     OrderDao orderDao;
     
     @Autowired
     OrderDetailDao orderDetailDao;
     
     @Autowired
     ProductService productService;
     
    @Override
    @Transactional //事务
    public boolean placeOrder(OrderDto dto) {
        boolean result = false;
        
        // 1.插入订单主表
        orderDao.insert(dto.getOrder()); /*OrderDao中insert()方法的@SelectKey(...) 会把插入后的id值赋给实体类BizOrder的id属性*/
        // 2.插入订单明细（循环）--订单是前端页面传过来的
        for (BizOrderDetail orderDetail : dto.getOrderDetail()) {
            orderDetail.setOrderId(dto.getOrder().getId());
            orderDetailDao.insert(orderDetail);
            // 2.1扣减商品库存
            productService.decreaseStock(orderDetail.getProductId(), orderDetail.getQuantity());
        }
        return result;
    }

}
